<template>
  <div class="upload_main">
    <!-- 文件上传 -->
    <div id="drop-zone" v-show="isUpload">
      <img
        src="../../../../assets/images/upload.png"
        alt=""
        class="w-[80px] h-[80px]"
      />
      <p class="font-bold text-[20px] mt-[32px]">点击或将文件拖拽至此处上传</p>
      <p class="text-[16px] text-[#A6A6A6] mt-[16px]">
        支持导入zip、7z、tar、gz、bz2、tgz等格式压缩包和xlsx、txt格式文件
      </p>
      <input type="file" id="file-input" multiple />
    </div>

    <!-- 进度条 -->
    <el-dialog
      v-model="isProgress"
      title="文件上传"
      width="440"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="relative">
        <div v-if="stopNext" class="text-[#E01B2B] mb-[16px] flex items-center">
          <el-icon class="mr-[4px]">
            <CircleCloseFilled />
          </el-icon>
          {{ title }}
        </div>
        <span class="mb-[16px]" v-else>{{ title }}</span>
        <el-progress
          :stroke-width="16"
          :color="stopNext ? '#E01B2B' : '#1a66ff'"
          :percentage="percentAge"
          class="mt-[16px]"
        />
      </div>
      <template #footer v-if="stopNext">
        <span class="dialog-footer">
          <Button type="cancel" @click="isProgress = false">取消导入</Button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
const fileList = ref([]);
const percentAge = ref(0);
const isUpload = ref(true);
const isProgress = ref(false);
const title = ref("");
const stopNext = ref(false); //接口反馈失败出现取消按钮，点击停止下一操作
const failState = ref(false);
let timerId;
const emit = defineEmits(["onChangeMenu"]);
const { selectData } = defineProps({
  selectData: {
    type: Object,
    default: {},
  },
});
// 打开上传初始展示的是上传
const openUpload = () => {
  isUpload.value = true;
  isProgress.value = false;
};
defineExpose({
  openUpload,
});
// 上传格式校验
const beforeUpload = (file) => {
  const extension = file.name.split(".").pop();
  const arr = [
    "zip",
    "7z",
    "tar",
    "gz",
    "gzip",
    "bz2",
    "bzip2",
    "tgz",
    "xlsx",
    "txt",
  ]; // 允许的格式列表
  if (extension && !arr.includes(extension)) {
    ElMessage.error(
      "上传文件只能是 zip、7z、tar、gz、gzip、bz2、bzip2、tgz、xlsx、txt格式!"
    );
    return false;
  }
  return true;
  //   if (file.size > 10 * 1024 * 1024) {
  //     ElMessage.error("上传文件大小不能超过 10MB!");
  //     return false;
  //   }
};
onMounted(() => {
  const dropZone = document.getElementById("drop-zone");
  const fileInput = document.getElementById("file-input");

  // 监听拖拽事件
  dropZone.addEventListener("dragover", (e) => {
    e.preventDefault();
    dropZone.classList.add("dragover"); // 添加拖拽样式
  });

  dropZone.addEventListener("dragleave", () => {
    dropZone.classList.remove("dragover"); // 移除拖拽样式
  });

  dropZone.addEventListener("drop", (e) => {
    e.preventDefault();
    dropZone.classList.remove("dragover"); // 移除拖拽样式
    const files = e.dataTransfer.files; // 获取拖拽的文件
    handleFiles(files); // 处理文件
    // 拖拽后也清空 input 值
    fileInput.value = '';
  });

  // 监听文件选择事件
  fileInput.addEventListener("change", (e) => {
    console.log('文件选择事件触发，文件数量:', e.target.files.length);
    const files = e.target.files; // 获取选择的文件
    handleFiles(files); // 处理文件
    // 立即清空 input 值，确保相同文件能再次选择
    e.target.value = '';
  });

  // 点击区域触发文件选择
  dropZone.addEventListener("click", () => {
    // 点击前先清空 input 值，确保相同文件能再次选择
    fileInput.value = '';
    fileInput.click(); // 触发文件输入框的点击事件
  });
});
// 选择的文件
const handleFiles = (files) => {
  console.log('handleFiles 被调用，文件数量:', files.length);
  
  if (!files.length) return;
  
  // 重置文件列表和状态
  fileList.value = [];
  percentAge.value = 0;
  stopNext.value = false;
  
  for (var i = 0; i < files.length; i++) {
    let flag = beforeUpload(files[i]);
    if (!flag) return;
    if (flag) {
      fileList.value.push({
        raw: files[i],
      });
    }
  }
  
  console.log('文件验证通过，准备上传，文件数量:', fileList.value.length);
  
  // 展示进度条
  if (fileList.value?.length) {
    title.value = "上传中";
    isProgress.value = true;
    isUpload.value = false;
    percentAge.value = 0;
    uploadFile();
    getSetInterval();
  }
  
};
// 定时器进度条
const getSetInterval = () => {
  timerId = setInterval(() => {
    if (percentAge.value > 90) {
      clearInterval(timerId);
    } else {
      percentAge.value = (percentAge.value % 100) + 9;
    }
  }, 200);
};
// 上传文件到服务器
const uploadFile = async () => {
  let formData = new FormData();
  // 将上传的文件放到数据对象中
  fileList.value.forEach((file) => {
    formData.append("files", file.raw);
  });
  const flag = selectData.id ? false : true;
  // 判断是继续上传还是新建上传
  const apiType = selectData.id
    ? api.upKeepload(selectData.id, formData)
    : api.upload(formData);
  let [err, res] = await apiType;
  fileList.value = [];
  clearInterval(timerId);
  
  // 上传完成后清空 input 值，确保相同文件能再次选择
  const fileInput = document.getElementById("file-input");
  if (fileInput) {
    fileInput.value = '';
  }
  
  // 接口反馈失败
  if (err) {
    stopNext.value = true;
    title.value = "文件过大，无法上传，请分批上传";
  } else {
    stopNext.value = false;
    percentAge.value = 100;
    emit("onChangeMenu", flag);
    isProgress.value = false;
    
    // 重置上传状态，确保可以继续上传
    setTimeout(() => {
      isUpload.value = true;
      percentAge.value = 0;
      stopNext.value = false;
      
    }, 1000);
    
    nextTick(() => {});
  }
};
</script>
<style lang="scss" scoped>
:deep(.el-progress__text) {
  position: absolute;
  top: -33px;
  right: -10px;
  color: rgba(0, 0, 0, 0.9);
  font-size: 16px;
}
.upload_title {
  font-size: 18px;
  font-weight: bold;
}
:deep(.el-progress) {
  width: 360px;
  height: 16px;
}
.upload_main {
  flex: 1;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  .upload-demo {
    width: 800px;
    height: 372px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2px dashed rgba(221, 221, 221, 1);
    border-radius: 10px;
    background: linear-gradient(
        180deg,
        rgba(230, 242, 255, 0.8),
        rgba(230, 242, 255, 0.16) 100%
      ),
      rgb(255, 255, 255);
    &:hover {
      border: 2px dashed rgb(26, 102, 255);
    }
  }
}
#drop-zone {
  width: 800px;
  height: 372px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed rgba(221, 221, 221, 1);
  border-radius: 10px;
  background: linear-gradient(
      180deg,
      rgba(230, 242, 255, 0.8),
      rgba(230, 242, 255, 0.16) 100%
    ),
    rgb(255, 255, 255);
  &:hover {
    border: 2px dashed rgb(26, 102, 255);
  }
  cursor: pointer;
}

#drop-zone.dragover {
  border-color: #000;
  background-color: #f0f0f0;
}

#file-input {
  display: none; /* 隐藏默认的文件输入框 */
}
</style>